<template>
	<view class="container">
		<tui-loading v-show="!pageData.loading"></tui-loading>
		<view class="page" v-show="pageData.loading" :style="{ 'marginTop': header.init.height + 'px' }">
			<tui-navigation-bar @init="initNavigation" @change="changeNavigation" :title="header.title"
				:color="tui.getColorSite().title.color" :backgroundColor="tui.getColorSite().title.backgroundColor"
				:splitLine="header.splitLine" :isOpacity="header.isOpacity" :maxOpacity="header.maxOpacity"
				:transparent="header.transparent" :scrollTop="header.scrollTop" :scrollRatio="header.scrollRatio"
				:isCustom="header.isCustom" :isImmersive="header.isImmersive" :isFixed="header.isFixed"
				:backdropFilter="header.backdropFilter" :dropDownHide="header.dropDownHide" :zIndex="header.zIndex">
				<view class="tui-header-icon" :style="{ top: header.init.top + 'px' }"
					v-if="!tui.inArray(get.tpl,['authList'])">
					<tui-icon name="arrowleft" :color="tui.getColorSite().title.color" @click="back"></tui-icon>
				</view>
			</tui-navigation-bar>
			<u-sticky bgColor="#fff">
				<u-tabs :list="pageData.tabs.data" :current="pageData.tabs.index" lineColor="#36B184" :lineWidth="40"
					:activeStyle="{ color: '#36B184' }" @click="tabsClick"></u-tabs>
			</u-sticky>
			<view class="tui-order-list">
				<view class="tui-order-item" v-for="(item, index) in listData.data" :key="index"
					@click="detail('orderInfo',item)">
					<tui-list-cell :hover="false" lineLeft="0">
						<view class="tui-item-title">
							<view>订单号：{{item.order_sn}}</view>
							<view class="tui-order-status" :style="{color: item.status_text_form.color}">
								{{item.status_text_form.title}}</view>
						</view>
					</tui-list-cell>
					<block v-for="(objItem,objIndex) in item.obj_info" :key="objIndex">
						<tui-list-cell padding="0">
							<view class="tui-item-goods">
								<image :src="objItem.log.data.picture.url" class="tui-goods-img"></image>
								<view>
									<view class="tui-goods-center">
										<view class="tui-goods-name">
											<tui-overflow-hidden :lineClamp="2">
												{{objItem.log.data.title}}
											</tui-overflow-hidden>
										</view>
										<view class="tui-goods-attr" v-if="objItem.log.data.keys">
											{{tui.arr2str(objItem.log.data.keys,',')}}
										</view>
									</view>
									<view class="tui-price-right">
										<text class="rightNums">x{{objItem.num}}</text>
										<text class="rightmoney">￥{{objItem.price}}</text>
									</view>
								</view>

							</view>

						</tui-list-cell>
					</block>
					<tui-list-cell :hover="false" unlined>
						<view class="tui-order-price">
							<view>共<text class="tui-color-red">{{item.num}}</text>件商品 合计：</view>
							<view class="tui-size-24 tui-color-red" v-if="item.paySite&&item.paySite.left">
								{{item.paySite.left}}</view>
							<view class="tui-price-large tui-color-red">{{item.paySite.sum_price}}</view>
							<view class="tui-size-24 tui-color-red" v-if="item.paySite&&item.paySite.right">
								{{item.paySite.right}}</view>
						</view>
					</tui-list-cell>
					<view class="tui-order-btn">
						<view class="tui-btn-ml" v-if="item.status==0&&tui.inArray(get.tpl,['def'])"
							@tap.stop="detail('delete',item)">
							<tui-button type="green" plain width="200rpx" height="58rpx" :size="26"
								shape="circle">取消订单</tui-button>
						</view>
						<view class="tui-btn-ml" v-if="item.status==0&&tui.inArray(get.tpl,['def'])"
							@tap.stop="detail('nowPay',item)">
							<tui-button type="green" plain width="200rpx" height="58rpx" :size="26"
								shape="circle">立即支付</tui-button>
						</view>
						<view class="tui-btn-ml" v-if="item.status==2&&tui.inArray(get.tpl,['def'])"
							@tap.stop="detail('sign',item)">
							<tui-button type="green" width="200rpx" height="58rpx" :size="26"
								shape="circle">确认收货</tui-button>
						</view>
						<view class="tui-btn-ml" v-if="item.status==1&&tui.inArray(get.tpl,['deliver_goods'])"
							@tap.stop="detail('deliver_goods',item)">
							<tui-button type="green" plain width="200rpx" height="58rpx" :size="26"
								shape="circle">立即发货</tui-button>
						</view>
						<view class="tui-btn-ml" @tap.stop="detail('publicInfo',{id:2,title:'联系客服',tpl:'agreement',})">
							<tui-button type="green" plain width="200rpx" height="58rpx" :size="26"
								shape="circle">联系客服</tui-button>
						</view>
					</view>
				</view>
			</view>
			<tui-loadmore :index="3" :type="tui.getColorSite().loadmore.type"
				v-if="listData.xhr.status && listData.status" :text="listData.xhr.text"></tui-loadmore>
			<tui-divider width="60%" :dividerColor="tui.getColorSite().divider.dividerColor"
				:color="tui.getColorSite().divider.color"
				v-if="!listData.xhr.status && listData.status">{{ listData.xhr.text }}</tui-divider>
			<view class="tui-safearea-bottom"></view>

			<t-pay-way :price="pageData.payWay.price" :paySite="pageData.payWay.paySite" :show="pageData.payWay.status"
				@btnPay="btnPay" @close="payWayClose"></t-pay-way>
		</view>
	</view>
</template>

<script>
	import tPayWay from "@/components/views/t-pay-way/t-pay-way"
	export default {
		components: {
			tPayWay,
		},
		data() {
			return {
				get: {},
				appInit: {},
				user: {},
				header: {
					title: '我的订单', //NavigationBar标题
					splitLine: true, //是否需要分割线
					isOpacity: false, //是否设置不透明度
					maxOpacity: 1, //不透明度最大值 0-1
					transparent: false, //背景透明 （设置该属性，则背景透明，只出现内容，isOpacity和maxOpacity失效）
					scrollTop: 0, //滚动条滚动距离
					scrollRatio: 0.3, //isOpacity 为true时生效（opacity=scrollTop /windowWidth * scrollRatio）
					isCustom: false, //是否自定义NavigationBar内容
					isImmersive: true, //是否沉浸式,
					isFixed: true, //是否固定
					backdropFilter: false, //是否开启高斯模糊效果[仅在支持的浏览器有效果]，为true时maxOpacity设置小于1的值
					dropDownHide: false, //下拉隐藏NavigationBar，主要针对有回弹效果ios端
					zIndex: 9998, //z-index值
					init: {
						width: 0,
						height: 0,
						left: 0,
						top: 0,
						top: 0,
						scrollH: 0,
					},
				},
				pageData: {
					loading: false,
					tabs: {
						index: -1,
						data: []
					},
					payWay: {
						status: false,
						price: '0',
						paySite: {},
					},
				},
				xhrUrl: '/goods',
				listData: {
					data: {},
					page: 0,
					length: 0,
					isMore: true,
					xhr: {
						url: '/goods',
						status: true,
						text: '正在加载...',
					},
					status: true,
				},
			}
		},
		// 监听页面加载，其参数为上个页面传递的数据，参数类型为 Object（用于页面传参）
		onLoad(e) {
			let that = this;
			// uni.startPullDownRefresh();
			console.log("self:onLoad++++++++++++++++++++++++++++++++++++++++++++++++++");
			uni.stopPullDownRefresh(); //停止当前页面下拉刷新
			if (typeof(e.scene) != 'undefined') {
				e = that.tui.getUrlkey(decodeURIComponent(e.scene));
			}
			that.get = e;
			that.get.tpl = that.get.tpl || 'def';
			if (typeof that.get.title !== 'undefined') {
				that.header.title = that.get.title;
				if (that.header.title.length > 13) {
					that.header.title = that.header.title.slice(0, 13) + '...';
				}
			}
			console.log("self:getData=>", that.get);
			let obj = {};
			uni.getSystemInfo({
				success: function(res) {
					that.header.init.width = obj.left || res.windowWidth;
					that.header.init.height = obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44;
					that.header.init.top = obj.top ? obj.top + (obj.height - 32) / 2 : res.statusBarHeight + 6;
					that.header.init.scrollH = res.windowWidth * 0.6;
				}
			});
			that.$forceUpdate();
			that.initialize();
		},
		// 监听页面显示。页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面
		onShow() {
			let that = this;
			// #ifdef MP-WEIXIN
			if (wx.hideHomeButton) {
				wx.hideHomeButton();
			}
			uni.$once('wxGetUserPhone', function(res) {
				console.log('监听到事件来自 wxGetUserPhone', res);
				that.userInfo = res.user;
				uni.$off('wxGetUserPhone')
			})
			// #endif
		},
		// 监听页面滚动，参数为Object
		onPageScroll(e) {
			let that = this;
			that.header.scrollTop = e.scrollTop;
			that.$forceUpdate();
		},
		methods: {
			initialize() {
				let that = this;
				let Int = setInterval(function() {
					that.user = that.tui.getCache("user");
					console.log('self:user=>', that.user);
					if (typeof(that.user) == 'object') {
						clearInterval(Int);
						that.__init();
					}
				}, 800);
			},
			async __init() {
				let that = this;
				that.appInit = that.tui.getCache("appInit");
				console.log('self:appInit=>', that.appInit);
				that.pageData.tabs.data.push({
					name: '全部',
					key: 'all',
				});
				that.user.orderData.forEach(function(tabItem, tabKey) {
					that.pageData.tabs.data.push({
						name: tabItem.text,
						key: tabItem.key,
					});
				});
				let tabsIndex = 0;
				that.pageData.tabs.data.forEach(function(tabItem, tabKey) {
					if (tabItem.key == that.get.key) {
						tabsIndex = tabKey;
					}
				});
				that.pageData.tabs.index = tabsIndex;
				that.pageData.loading = true;
				that.initList();
			},
			tabsClick(e) {
				let that = this;
				that.listData.xhr.text = '正在获取 ... ...';
				that.pageData.tabs.index = e.index;
				that.listData.page = 0;
				that.initList();
			},
			async detail(type, item = {}) {
				let that = this;
				switch (type) {
					case 'orderInfo':
						that.tui.urlHref('/pages/order-info?' + that.tui.initParamsData({
							id: item.id,
							tpl: that.get.tpl,
						}));
						break;
					case 'deliver_goods':
						that.tui.urlHref('/pages/order-info?' + that.tui.initParamsData({
							title: '订单发货',
							id: item.id,
							tpl: that.get.tpl,
							actionStatus: 1,
						}));
						break;
					case 'delete':
						that.tui.confirm('取消订单', '确定取消订单？', function(action) {
							if (action.confirm) {
								that.tui.del(that.xhrUrl, {
									order: that.tui.formatDate().timestamp,
									delete: that.tui.formatDate().timestamp,
									type: 'cancel',
								}, {
									order_id: item.id
								}).then(function(response) {
									that.listData.page = 0;
									that.initList();
								});
							}
						});
						break;
					case 'sign':
						let signParam = {};
						signParam.order_id = item.id;
						let signResponse = await that.tui.put(that.xhrUrl, signParam, {
							order: that.tui.formatDate().timestamp,
							sign: that.tui.formatDate().timestamp
						});
						that.tui.toast(signResponse.info, false, function() {
							switch (signResponse.status) {
								case 0:
									that.listData.page = 0;
									that.initList();
									break;
								default:
									// that.tui.toast(signResponse.info, 'none', function() {}, 1500);
									break;
							}
						}, 1500);
						break;
					case 'nowPay':
						that.pageData.payWay.price = item.total_price;
						let index = 0;
						for (let item in that.appInit.paySite) {
							that.appInit.paySite[item].info = '';
							switch (that.appInit.paySite[item].key) {
								case "balance":
									if (that.user.userInfo.balance * 100 < that.pageData.payWay.price * 100) {
										that.appInit.paySite[item].info = '余额不足请充值';
									}
									break;
								case "u_pay":
									if (that.user.userInfo.u_species * 100 < that.pageData.payWay.price / that.tui
										.str2arr(that.appInit.integral2u_species, ':')[1]) {
										that.appInit.paySite[item].info = 'U币不足';
									} else {
										that.appInit.paySite[item].info = 'U币支付' + that.pageData.payWay.price / that
											.tui.str2arr(that.appInit.integral2u_species, ':')[1];
									}
									break;
							}
							if (that.tui.inArray(index, [0])) {
								that.appInit.paySite[item].status = true;
							} else {
								that.appInit.paySite[item].status = false;
							}
							index++;
						}
						that.pageData.payWay.paySite = that.appInit.paySite;
						that.pageData.payWay.order_id = item.id;
						that.pageData.payWay.status = true;
						return;
						let payParam = {};
						payParam.id = item.id;
						payParam.pay_fun = 2;
						payParam.ambient = 2;
						// #ifdef H5
						// payParam.pay_fun = 1;
						// payParam.ambient = 2;
						// #endif
						let payResponse = await that.tui.post(that.xhrUrl, payParam, {
							pay: that.tui.formatDate().timestamp
						});
						switch (payResponse.status) {
							case 0:
								// #ifdef MP-WEIXIN
								that.tui.wxPay(payResponse.data.paySite, function(res) {
									that.tui.toast('支付成功！', 'none', function() {
										that.listData.page = 0;
										that.initList();
									}, 1000)
								}, function(err) {
									//跳转到我的订单页
									that.tui.toast('取消支付！', 'none', function() {}, 1500);
								});
								// #endif
								// #ifndef MP-WEIXIN
								console.log(payResponse);
								// #endif
								break;
							default:
								that.tui.toast(payResponse.info, 'none', function() {
									// that.actionsheetClose();
								}, 1500);
								break;
						}
						break;
					case 'publicInfo':
						that.tui.urlHref('/pages/public-info?' + that.tui.initParamsData({
							title: item.title,
							tpl: item.tpl,
							id: item.id,
							timestamp: that.tui.formatDate().timestamp
						}));
						break;
					default:
						console.log(that.get.tpl, type, item);
						break;
				}
				that.$forceUpdate();
			},
			payWayClose() {
				let that = this;
				that.pageData.payWay.status = false;
			},
			async btnPay(e) {
				let that = this;
				let payParam = {};
				payParam.pay_fun = e.payKey;
				payParam.ambient = 0;
				payParam.order_id = that.pageData.payWay.order_id;
				switch (e.payKey) {
					case 2:
					case 3:
						console.log(that.param);
						return;
						break;
				}
				let response = await that.tui.put(that.xhrUrl, payParam, {
					order: that.tui.formatDate().timestamp,
					pay: that.tui.formatDate().timestamp,
				}, true, true, false);
				that.tui.toast(response.info, false, function() {
					switch (response.status) {
						case 0:
							switch (e.payKey) {
								case 2:
								case 3:
									console.log(that.param);
									break;
								default:
									that.tui.setUserInfo(response.data.userInfo, function(response) {
										that.listData.page = 0;
										that.initList();
									});
									break;
							}
							break;
						default:
							break;
					}
				}, 1500);
			},
			async initList() {
				let that = this;
				if (that.listData.xhr.url === false) {
					that.listData.status = false;
					return;
				}
				if (that.listData.page == 0) {
					that.listData.data = [];
					that.listData.isMore = true;
					that.listData.status = true;
				}
				let param = {
					page: that.listData.page,
					length: that.tui.requestPageLength,
					order: that.tui.formatDate().timestamp,
				};
				param.type = that.pageData.tabs.data[that.pageData.tabs.index].key;
				param.mapKey = that.get.tpl;
				let response = await that.tui.get(that.listData.xhr.url, param);
				switch (response.status) {
					case 0:
						response = response.data;
						// 当前分页为0的时候 返回数据为0  暂无数据
						if (response.count == 0) {
							that.listData.isMore = false;
							that.listData.xhr.status = false;
							that.listData.xhr.text = '暂无数据... ...';
						} else {
							if (that.listData.page == 0) {
								if (response.data.length < param.length) {
									that.listData.status = false;
								}
							}
							that.listData.data = that.listData.data.concat(response.data);
							if (response.data.length < param.length) {
								that.listData.isMore = false;
								that.listData.xhr.status = false;
								if (response.data.length != 0) {
									that.listData.xhr.text = '没有更多啦 ... ...';
								}
							}
						}
						break;
					default:
						that.tui.toast(response.info, false, function() {
							that.listData.isMore = false;
							that.listData.xhr.status = false;
							that.listData.xhr.text = response.info;
						}, 1500);
						break;
				}
				that.$forceUpdate();
			},
			initNavigation(e) {
				let that = this;
				that.header.opacity = e.opacity;
				that.header.top = e.top;
				that.$forceUpdate();
			},
			changeNavigation(e) {
				let that = this;
				that.header.opacity = e.opacity;
				that.$forceUpdate();
			},
			back() {
				let that = this;
				that.tui.urlBack(1);
			},
		},
		// 页面滚动到底部的事件（不是scroll-view滚到底），常用于下拉下一页数据
		onReachBottom() {
			let that = this;
			if (that.listData.isMore == true) {
				that.listData.page++
				that.initList();
			}
		},
		// 监听页面隐藏
		onHide() {
			let that = this;
		},
		// 监听页面卸载
		onUnload() {
			let that = this;
		},
		// 页面返回
		onBackPress() {
			let that = this;
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage() {
			console.log('分享!')
		},
		// #endif
	}
</script>

<style scoped lang="scss">
	.tui-order-list {
		margin-top: -20rpx;

		.tui-order-item {
			margin-top: 20rpx;
			border-radius: 10rpx;
			overflow: hidden;

			.tui-item-title {
				width: 100%;
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 24rpx;
				color: #999999;

				.tui-order-status {
					color: #888;
					font-size: 24rpx;
					color: #36B184;
				}
			}

			.tui-item-goods {
				width: 100%;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				display: flex;

				// justify-content: space-between;

				.tui-goods-img {
					width: 180rpx;
					height: 180rpx;
					display: block;
					flex-shrink: 0;
					margin-right: 20rpx;
				}

				.tui-goods-center {
					flex: 1;
					padding: 20rpx 8rpx;
					box-sizing: border-box;

					.tui-goods-name {
						// max-width: 310rpx;
						word-break: break-all;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						font-size: 26rpx;
						line-height: 32rpx;

					}

					.tui-goods-attr {
						font-size: 22rpx;
						color: #888888;
						line-height: 32rpx;
						padding-top: 20rpx;
						word-break: break-all;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
					}
				}

				.tui-price-right {
					line-height: 30rpx;
					padding-top: 20rpx;
					display: flex;
					justify-content: space-between;
					margin: 0 16rpx;
					.rightNums{
						font-size: 24rpx;
						color: #6F6F6F;
					}
					.rightmoney{
						color: #333333;
						font-size: 30rpx;
					}
				}
			}

			.tui-order-price {
				width: 100%;
				display: flex;
				align-items: flex-end;
				justify-content: flex-end;
				font-size: 24rpx;
			}

			.tui-order-btn {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				background: #fff;
				padding: 10rpx 30rpx 20rpx;
				box-sizing: border-box;

				.tui-btn-ml {
					margin-left: 20rpx;
					position: relative;
				}
			}
		}
	}
</style>